package com.gitee.zhangchenyan.takin.common.inject;

import com.gitee.zhangchenyan.takin.common.result.Result;
import com.gitee.zhangchenyan.takin.common.result.ResultCode;
import com.gitee.zhangchenyan.takin.common.result.ResultUtils;
import com.gitee.zhangchenyan.takin.common.utils.ExceptionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.naming.AuthenticationException;
import javax.security.auth.message.AuthException;
import java.lang.reflect.UndeclaredThrowableException;

/**
 * 全局捕获异常 使用AOP技术，采用异常通知方法
 * 1、捕获返回json格式
 * 2、捕获返回页面
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result errorResult(Exception ex) {


        if (ex instanceof UndeclaredThrowableException) {
            //代理调用特殊处理
            UndeclaredThrowableException undeclaredThrowableException = (UndeclaredThrowableException) ex;
            if (undeclaredThrowableException.getUndeclaredThrowable() instanceof AuthException) {
                return ResultUtils.notLogin();
            }
            ExceptionUtils.outputStr(undeclaredThrowableException.getUndeclaredThrowable(), "代理");
            return ResultUtils.unknown(undeclaredThrowableException.getUndeclaredThrowable().getMessage());
        }

        if (ex.getClass().equals(AuthException.class)) {
            return ResultUtils.notLogin();
        }
        if (ex.getClass().equals(AuthenticationException.class)) {
            Result result = new Result();
            result.setCode(ResultCode.NOT_AUTHORITY);
            result.setMessage(ex.getMessage());
            return result;
        }
        String outException = ExceptionUtils.outputStr(ex, "全局");
        return ResultUtils.unknown(outException);
    }


}
